﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO.Ports;
using WebSocketSharp;
using DidaManager.Log;
using System.Threading;
using System.Timers;
using DidaManager.Native.RemoteTransmission;

namespace DidaManagerOnline.Native.RemoteTransmission
{
    class HeartbeatManager
    {
        private WebSocket ws;
        private bool hasData;
        private System.Timers.Timer timer;
        private bool bTimeStop = false;

        public HeartbeatManager(WebSocket websocket)
        {
            this.ws = websocket;
            this.hasData = false;
            this.bTimeStop = false;

            timer = new System.Timers.Timer();
            timer.AutoReset = true;
            timer.Enabled = true;
            timer.Interval = 30000;
            timer.Elapsed += new System.Timers.ElapsedEventHandler(SendHeartbeat);
        }

        private void SendHeartbeat(object? sender, ElapsedEventArgs e)
        {
            if (!hasData && ws.IsAlive)
            {
                // 没有数据传输，发送心跳消息
                ws.Ping();
                LogManager.Debug("timer 30s ping: ");
            }
            else
            {
                hasData = false;
            }
        }

        public void DataReceived()
        {
            hasData = true;
            if(!bTimeStop)
            {
                timer.Stop();
                timer.Start();
            }
        }

        public void Stop()
        {
            timer.Stop();
            timer.Dispose();
            bTimeStop = true;
        }
    }

    public class TransWebSocketClient
    {
        private WebSocket _ws;
        private readonly object _serialPortLock = new object();
        public event EventHandler<MessageEventArgs>? MessageReceived;
        public delegate void ConnectStatusHandler(string data);
        public event ConnectStatusHandler? ConnectStatus;
        private bool bManualClose = false;// 是否是手动关闭
        private HeartbeatManager? heartbeatManager = null;

        static public string GetWebSocketPath(string address, int port)
        {
            string protocol = "ws"; // 或者使用 "wss" 如果需要安全连接

            // 构建 WebSocket 路径
            string webSocketPath = $"{protocol}://{address}:{port}/ws";

            return webSocketPath;
        }


        public TransWebSocketClient(string url,string idValue)
        {
            _ws = new WebSocket(url);

            var keyValuePairsList = new List<KeyValuePair<string, string>>
            {
                new KeyValuePair<string, string>("id", idValue),
            };
            IEnumerable<KeyValuePair<string, string>> keyValuePairs = keyValuePairsList;
            _ws.CustomHeaders = keyValuePairsList;

            _ws.OnMessage += (sender, e) =>
            {
                OnMessageReceived(e);
            };
            _ws.OnOpen += (sender, e) =>
            {
                LogManager.Debug("WebSocket connection opened.");
                var timer = new System.Timers.Timer(300);
                timer.AutoReset = false; // 设置为 false，使定时器只触发一次
                timer.Elapsed += (sender, e) =>
                {
                    ConnectStatus?.Invoke("start");
                    StartHeartbeat();
                    // 在定时器间隔之后执行操作
                    timer.Stop(); // 停止定时器
                };
                timer.Start();
            };

            _ws.OnClose += (sender, e) =>
             {
                 LogManager.Debug("WebSocket connection closed.");
                 //ConnectStatus?.Invoke("disconnect");// 这里触发已经来不及了，需要在websocket断开前就发送
                 if(!bManualClose)//手动关闭不自动重连
                 {
                     Connect();
                 }
             };

            _ws.OnError += (sender, e) =>
                LogManager.Error("WebSocket error: " + e.Message);
        }

        public void Connect()
        {
            bManualClose = false;
            _ws.Connect();
            LogManager.Debug("WebSocket connection.");
        }
        public bool IsAlive()
        {
            return _ws.IsAlive;
        }
        public bool IsConnected()
        {
            if (_ws.ReadyState == WebSocketState.Open)
            {
                return true;
            }
            return false;
        }


        public void SendMessage(string message)
        {
            if (_ws.ReadyState != WebSocketState.Open)
            {
                LogManager.Debug("websocket is closed ,the message send is failed"+message);
                return;
            }
            ReqTransWebsocketData reqData = new ReqTransWebsocketData(message);
            string data = reqData.ToJson();
            LogManager.Debug("Websocket SendMessage: " + data);

            _ws.Send(data);
            Heartbeat();
        }

        protected virtual void OnMessageReceived(MessageEventArgs e)
        {
            LogManager.Debug(e.Data);
            MessageReceived?.Invoke(this, e);
            Heartbeat();
        }

        public void Close()
        {
            bManualClose = true;
            _ws.Close();
            if(heartbeatManager != null)
            {
                heartbeatManager.Stop();
            }
        }

        void StartHeartbeat()
        {
            TimeSpan checkInterval = TimeSpan.FromSeconds(30); // 数据检查间隔
            TimeSpan heartbeatInterval = TimeSpan.FromSeconds(30); // 心跳发送间隔
            if (heartbeatManager != null)
            {
                heartbeatManager.Stop();
            }
            heartbeatManager = new HeartbeatManager(_ws);
        }

        void Heartbeat()// 有收发数据触发
        {
            if (_ws != null && _ws.IsAlive && heartbeatManager != null)
            {
                heartbeatManager.DataReceived();
            }           
        }
    }

}
